package com.wealth.scsj.p_app.model;


import com.wealth.scsj.p_app.api.APIService;
import com.wealth.scsj.p_app.baseurl.BaseUrl;
import com.wealth.scsj.p_app.bean.BaseBean;

import dkmvp.net.HttpService;
import dkmvp.net.ResponseCallback;
import dkmvp.net.ResponseHandler;
import dkmvp.net.RetryWithDelay;
import rx.Observable;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * 基础 model ，在这里实现网络请求
 */

public class BaseModel {

    public HttpService httpService;
    public APIService service;

    public BaseModel() {
        httpService = HttpService.getInstance(BaseUrl.BASE_URL,false);
        service = httpService.getHttpService().create(APIService.class);
    }

    public BaseModel(boolean has_cache) {
        httpService = HttpService.getInstance(BaseUrl.BASE_URL,has_cache);
        service = httpService.getHttpService().create(APIService.class);
    }

    public Subscription getData(Observable observable, final ResponseCallback callback){

        Subscription sub = observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .retryWhen(new RetryWithDelay(3, 3000))//总共重试3次，重试间隔3秒
                .subscribe(new Action1<BaseBean>() {
                    @Override
                    public void call(BaseBean result) {
                        callback.onSuccess(result);
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        callback.onFaild(ResponseHandler.getErrorMsg(throwable));
                    }
                });
        return  sub;
    }
}
